from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.generics import CreateAPIView, RetrieveAPIView,GenericAPIView, ListAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from questions.models import Questions, Answer
from .models import User, Homepage, Archives

from .serializers import CreateUserSerializer, HomepageSerializer, ArchivesSerializer, MyQuestionsSerializer


class UsernameCountView(APIView):
    """用户名数量"""
    def get(self, request, username):
        """获取指定用户名的数量"""
        count = User.objects.filter(username=username).count()

        data = {
            "username": username,
            "count": count
        }
        return Response(data=data)


class MobileCountView(APIView):
    """手机号数量"""
    def get(self, request, mobile):
        """获取指定手机号的数量"""
        mobile_count = User.objects.filter(mobile=mobile).count()

        data = {
            "mobile": mobile,
            "count": mobile_count
        }
        return Response(data)


class UserView(CreateAPIView):
    """用户注册"""
    serializer_class = CreateUserSerializer


#
class HomepageView(RetrieveAPIView):

    permission_classes = [IsAuthenticated]
    serializer_class = HomepageSerializer

    def get_object(self):
        return Homepage.objects.get(user=self.request.user)

    # def get(self, request):
    #
    #     return Response(data=HomepageSerializer(self.get_object()).data)


    #

    # 方法二
    # class HomepageView(GenericAPIView):
    # def get(self,request):
    #     obj = self.get_queryset()
    #     s =  HomepageSerializer(obj.get())
    #     return Response(data=s.data,status=status.HTTP_200_OK)
    # #
    # def get_queryset(self):
    #     user = self.request.user
    #     return Homepage.objects.filter(user=user)

    # 方法三
    # class HomepageView(GenericAPIView):
    # def get_object(self):
    #     return Homepage.objects.get(user=self.request.user)
    #
    # def get(self,request):
    #     return Response(data=HomepageSerializer(self.get_object()).data)







class ArchivesView(RetrieveAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = ArchivesSerializer

    def get_object(self):
        return Archives.objects.get(user=self.request.user)


class MyQuestions(ListAPIView):

    """
    返回我的问题
    """

    serializer_class = MyQuestionsSerializer

    def get_queryset(self):
        user_id = self.request.user.id
        return Questions.objects.filter(author_name=user_id)


class MyAnswer(ListAPIView):
    """
    返回我回答的问题
    """
    serializer_class = MyQuestionsSerializer

    def get_queryset(self):
        user_id = self.request.user.id
        questions_list = Answer.objects.filter(user=user_id).only('question')
        return Questions.objects.filter(id__in=questions_list)

